<template>
  <div class="schedule-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <h1>日程汇总</h1>
        <p class="subtitle">各院校重要时间节点统一展示</p>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="container">
      <!-- 面包屑导航 -->
      <Breadcrumb />
      
      <div class="main-content">
        <!-- 时间提醒 -->
        <el-alert
          title="时间提醒"
          type="info"
          :closable="false"
          show-icon
          class="notice-alert"
        >
          <template #default>
            <div class="notice-content">
              <p><strong>提醒：</strong>请密切关注各院校的重要时间节点，合理安排时间</p>
              <p>时间如有变动，以各院校官方最新通知为准</p>
            </div>
          </template>
        </el-alert>

        <!-- 筛选条件 -->
        <el-card class="filter-card" shadow="never">
          <el-form :inline="true" :model="filterForm">
            <el-form-item label="院校名称">
              <el-input 
                v-model="filterForm.schoolName" 
                placeholder="请输入院校名称" 
                clearable 
                style="width: 200px"
                @input="filterSchedules"
              />
            </el-form-item>
            <el-form-item label="年度">
              <el-select 
                v-model="filterForm.year" 
                placeholder="选择年度" 
                clearable 
                style="width: 120px"
                @change="loadSchedules"
              >
                <el-option :value="2025" label="2025年" />
                <el-option :value="2024" label="2024年" />
              </el-select>
            </el-form-item>
            <el-form-item label="事项类型">
              <el-select 
                v-model="filterForm.eventType" 
                placeholder="选择事项" 
                clearable 
                style="width: 140px"
                @change="filterSchedules"
              >
                <el-option value="registration" label="报名时间" />
                <el-option value="qualified" label="入围公布" />
                <el-option value="payment" label="缴费时间" />
                <el-option value="exam" label="考试时间" />
                <el-option value="admission" label="录取时间" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="filterSchedules">搜索</el-button>
              <el-button @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 日程时间线 -->
        <el-card class="timeline-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h2><el-icon><Calendar /></el-icon> 重要时间节点</h2>
              <div class="header-info">
                <el-tag type="success">
                  <el-icon><InfoFilled /></el-icon>
                  共 {{ filteredSchedules.length }} 个事项
                </el-tag>
              </div>
            </div>
          </template>

          <el-timeline v-if="groupedSchedules.length > 0">
            <el-timeline-item 
              v-for="(group, index) in paginatedGroups" 
              :key="index"
              :timestamp="group.date || '时间待定'"
              placement="top"
              :type="getTimelineType(group)"
              size="large"
            >
              <div class="timeline-content">
                <h3 class="date-title">{{ group.date || '时间待定' }}</h3>
                <div class="events-list">
                  <div 
                    v-for="event in group.events" 
                    :key="event.id"
                    class="event-item"
                    :class="getEventClass(event)"
                  >
                    <div class="event-header">
                      <span class="school-name">{{ event.schoolName }}</span>
                      <el-tag 
                        :type="getEventTagType(event.eventType)" 
                        size="small" 
                        class="event-tag"
                      >
                        {{ getEventTypeName(event.eventType) }}
                      </el-tag>
                    </div>
                    <div class="event-details">
                      <p class="event-description">{{ event.description }}</p>
                      <div class="event-actions" v-if="event.actionUrl">
                        <el-button 
                          type="primary" 
                          size="small"
                          @click="goToEventAction(event)"
                        >
                          {{ getActionButtonText(event.eventType) }}
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>

          <!-- 分页 -->
          <div class="pagination-wrapper" v-if="groupedSchedules.length > groupsPerPage">
            <el-pagination
              v-model:current-page="groupPagination.page"
              :total="groupedSchedules.length"
              :page-size="groupsPerPage"
              layout="prev, pager, next"
              @current-change="handleGroupPageChange"
            />
          </div>

          <!-- 空状态 -->
          <el-empty 
            v-if="!loading && filteredSchedules.length === 0"
            description="暂无日程信息"
            :image-size="120"
          />
        </el-card>

        <!-- 表格视图 -->
        <el-card class="table-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h2><el-icon><List /></el-icon> 详细日程表</h2>
              <div class="view-toggle">
                <el-radio-group v-model="viewMode" size="small">
                  <el-radio-button value="timeline">时间线视图</el-radio-button>
                  <el-radio-button value="table">表格视图</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>

          <el-table 
            v-if="viewMode === 'table'"
            v-loading="loading" 
            :data="paginatedSchedules" 
            stripe 
            style="width: 100%"
            :header-cell-style="{ 'background-color': '#f5f7fa', 'color': '#303133', 'font-weight': '500' }"
          >
            <el-table-column 
              prop="schoolName" 
              label="院校名称" 
              min-width="250"
              show-overflow-tooltip
            />
            
            <el-table-column 
              prop="eventType" 
              label="事项类型" 
              width="120"
              align="center"
            >
              <template #default="{ row }">
                <el-tag :type="getEventTagType(row.eventType)" size="small">
                  {{ getEventTypeName(row.eventType) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column 
              label="时间安排" 
              width="200"
              align="center"
            >
              <template #default="{ row }">
                <div class="time-info">{{ getEventTimeRange(row) }}</div>
              </template>
            </el-table-column>
            
            <el-table-column 
              prop="description" 
              label="说明" 
              min-width="200"
              show-overflow-tooltip
            />
            
            <el-table-column 
              label="操作" 
              width="100"
              align="center"
              fixed="right"
            >
              <template #default="{ row }">
                <el-button 
                  v-if="row.actionUrl"
                  type="primary" 
                  size="small"
                  @click="goToEventAction(row)"
                >
                  {{ getActionButtonText(row.eventType) }}
                </el-button>
                <span v-else class="no-action">-</span>
              </template>
            </el-table-column>
          </el-table>

          <!-- 表格分页 -->
          <div 
            class="pagination-wrapper" 
            v-if="viewMode === 'table' && filteredSchedules.length > 0"
          >
            <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.size"
              :total="filteredSchedules.length"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handlePageChange"
              @current-change="handlePageChange"
            />
          </div>
        </el-card>

        <!-- 重要提醒 -->
        <el-card class="reminder-card" shadow="never">
          <template #header>
            <h2><el-icon><Bell /></el-icon> 重要提醒</h2>
          </template>
          <div class="reminder-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <h3>时间节点说明</h3>
                <ul>
                  <li><strong>报名时间：</strong>各院校开放报名的时间段</li>
                  <li><strong>入围公布：</strong>各院校公布入围名单的时间</li>
                  <li><strong>缴费时间：</strong>入围考生需要完成缴费的时间</li>
                  <li><strong>考试时间：</strong>各院校组织校测的时间</li>
                  <li><strong>录取时间：</strong>各院校公布录取结果的时间</li>
                </ul>
              </el-col>
              <el-col :span="12">
                <h3>注意事项</h3>
                <ul>
                  <li>时间安排可能因特殊情况发生调整</li>
                  <li>请以各院校官方最新通知为准</li>
                  <li>建议提前关注重要时间节点</li>
                  <li>错过关键时间可能影响报考资格</li>
                  <li>如有疑问请及时联系相关院校</li>
                </ul>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Calendar, InfoFilled, List, Bell } from '@element-plus/icons-vue'
import Breadcrumb from '@/components/Breadcrumb.vue'
import api from '@/api'

// 响应式数据
const loading = ref(false)
const scheduleData = ref([])
const filteredSchedules = ref([])
const viewMode = ref('timeline')

const filterForm = reactive({
  schoolName: '',
  year: 2025,
  eventType: ''
})

const pagination = reactive({
  page: 1,
  size: 20
})

const groupPagination = reactive({
  page: 1
})

const groupsPerPage = 5 // 每页显示的时间组数

// 计算属性
const paginatedSchedules = computed(() => {
  const start = (pagination.page - 1) * pagination.size
  const end = start + pagination.size
  return filteredSchedules.value.slice(start, end)
})

// 按日期分组的日程
const groupedSchedules = computed(() => {
  const groups = {}
  
  filteredSchedules.value.forEach(item => {
    const date = item.eventDate || '时间待定'
    if (!groups[date]) {
      groups[date] = {
        date,
        events: []
      }
    }
    groups[date].events.push(item)
  })
  
  return Object.values(groups).sort((a, b) => {
    if (a.date === '时间待定') return 1
    if (b.date === '时间待定') return -1
    return a.date.localeCompare(b.date)
  })
})

const paginatedGroups = computed(() => {
  const start = (groupPagination.page - 1) * groupsPerPage
  const end = start + groupsPerPage
  return groupedSchedules.value.slice(start, end)
})

// 方法
const loadSchedules = async () => {
  loading.value = true
  try {
    const { data } = await api.get('/annual-enrollment/by-type', {
      params: {
        year: filterForm.year || 2025,
        type: 'all' // 获取所有类型的数据
      }
    })
    
    // 将数据转换为日程格式
    const schedules = []
    data?.forEach(item => {
      // 报名时间
      if (item.registrationStartTime || item.registrationEndTime) {
        schedules.push({
          id: `${item.id}_registration`,
          schoolName: item.schoolName,
          eventType: 'registration',
          eventDate: item.registrationStartTime,
          description: `报名时间：${item.registrationStartTime || '待定'} - ${item.registrationEndTime || '待定'}`,
          actionUrl: item.registrationUrl,
          startTime: item.registrationStartTime,
          endTime: item.registrationEndTime
        })
      }
      
      // 入围公布
      if (item.qualifiedAnnounceTime) {
        schedules.push({
          id: `${item.id}_qualified`,
          schoolName: item.schoolName,
          eventType: 'qualified',
          eventDate: item.qualifiedAnnounceTime,
          description: `入围名单公布：${item.qualifiedAnnounceTime}`,
          actionUrl: item.qualifiedQueryUrl
        })
      }
      
      // 缴费时间
      if (item.paymentStartTime || item.paymentEndTime) {
        schedules.push({
          id: `${item.id}_payment`,
          schoolName: item.schoolName,
          eventType: 'payment',
          eventDate: item.paymentStartTime,
          description: `缴费时间：${item.paymentStartTime || '待定'} - ${item.paymentEndTime || '待定'}`,
          actionUrl: item.paymentUrl,
          startTime: item.paymentStartTime,
          endTime: item.paymentEndTime
        })
      }
      
      // 考试时间
      if (item.examTime) {
        schedules.push({
          id: `${item.id}_exam`,
          schoolName: item.schoolName,
          eventType: 'exam',
          eventDate: item.examTime,
          description: `考试时间：${item.examTime}`,
          actionUrl: item.examOutlineUrl
        })
      }
      
      // 录取时间
      if (item.admissionListReleaseTime) {
        schedules.push({
          id: `${item.id}_admission`,
          schoolName: item.schoolName,
          eventType: 'admission',
          eventDate: item.admissionListReleaseTime,
          description: `录取名单公布：${item.admissionListReleaseTime}`,
          actionUrl: item.admissionListUrl
        })
      }
    })
    
    scheduleData.value = schedules
    filterSchedules()
  } catch (error) {
    console.error('加载日程信息失败:', error)
    ElMessage.error('加载日程信息失败')
  } finally {
    loading.value = false
  }
}

const filterSchedules = () => {
  let result = scheduleData.value

  // 按院校名称筛选
  if (filterForm.schoolName) {
    result = result.filter(item => 
      item.schoolName && item.schoolName.includes(filterForm.schoolName)
    )
  }

  // 按事项类型筛选
  if (filterForm.eventType) {
    result = result.filter(item => item.eventType === filterForm.eventType)
  }

  filteredSchedules.value = result
  pagination.page = 1
  groupPagination.page = 1
}

const resetFilter = () => {
  Object.assign(filterForm, {
    schoolName: '',
    year: 2025,
    eventType: ''
  })
  loadSchedules()
}

// 获取事项类型名称
const getEventTypeName = (type) => {
  const typeMap = {
    registration: '报名',
    qualified: '入围',
    payment: '缴费',
    exam: '考试',
    admission: '录取'
  }
  return typeMap[type] || type
}

// 获取事项标签类型
const getEventTagType = (type) => {
  const typeMap = {
    registration: 'primary',
    qualified: 'success',
    payment: 'warning',
    exam: 'info',
    admission: 'danger'
  }
  return typeMap[type] || 'default'
}

// 获取时间线类型
const getTimelineType = (group) => {
  // 根据日期判断时间线颜色
  if (group.date === '时间待定') return 'warning'
  
  const now = new Date()
  const currentMonth = now.getMonth() + 1
  
  if (currentMonth >= 3 && currentMonth <= 4) {
    return 'success'
  } else if (currentMonth < 3) {
    return 'primary'
  } else {
    return 'info'
  }
}

// 获取事件样式类
const getEventClass = (event) => {
  return `event-${event.eventType}`
}

// 获取操作按钮文本
const getActionButtonText = (type) => {
  const textMap = {
    registration: '去报名',
    qualified: '查入围',
    payment: '去缴费',
    exam: '查考纲',
    admission: '查录取'
  }
  return textMap[type] || '查看'
}

// 获取事件时间范围
const getEventTimeRange = (event) => {
  if (event.startTime && event.endTime) {
    return `${event.startTime} - ${event.endTime}`
  }
  return event.eventDate || '时间待定'
}

// 跳转到事件操作页面
const goToEventAction = (event) => {
  if (event.actionUrl && event.actionUrl !== '#') {
    window.open(event.actionUrl, '_blank')
  } else {
    ElMessage.warning('该功能暂未开通')
  }
}

const handlePageChange = () => {
  // 分页变化处理
}

const handleGroupPageChange = () => {
  // 组分页变化处理
}

// 初始化
onMounted(() => {
  loadSchedules()
})
</script>

<style lang="scss" scoped>
.schedule-page {
  .page-header {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    color: white;
    padding: 60px 0;
    text-align: center;
    
    h1 {
      font-size: 2.5rem;
      margin-bottom: 16px;
      font-weight: 600;
    }
    
    .subtitle {
      font-size: 1.2rem;
      opacity: 0.9;
    }
  }
  
  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }
  
  .main-content {
    margin-top: -40px;
    position: relative;
    z-index: 1;
    
    .el-card {
      margin-bottom: 30px;
      border-radius: 12px;
      
      .el-card__header {
        background: #f8f9fa;
        border-bottom: 1px solid #e9ecef;
        
        h2 {
          margin: 0;
          color: #495057;
          display: flex;
          align-items: center;
          gap: 8px;
        }
      }
    }
    
    .notice-alert {
      margin-bottom: 20px;
      
      .notice-content {
        p {
          margin: 8px 0;
          font-size: 14px;
          line-height: 1.6;
          
          &:first-child {
            margin-top: 0;
          }
          
          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
    
    .filter-card {
      .el-form {
        margin: 0;
      }
    }
    
    .timeline-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .header-info {
          .el-tag {
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }
      }
      
      .timeline-content {
        .date-title {
          margin: 0 0 16px;
          color: #303133;
          font-size: 18px;
        }
        
        .events-list {
          .event-item {
            margin-bottom: 16px;
            padding: 16px;
            border-radius: 8px;
            border-left: 4px solid;
            
            &.event-registration {
              background: #f0f9ff;
              border-left-color: #409eff;
            }
            
            &.event-qualified {
              background: #f0f9f0;
              border-left-color: #67c23a;
            }
            
            &.event-payment {
              background: #fdf6ec;
              border-left-color: #e6a23c;
            }
            
            &.event-exam {
              background: #f4f4f5;
              border-left-color: #909399;
            }
            
            &.event-admission {
              background: #fef0f0;
              border-left-color: #f56c6c;
            }
            
            &:last-child {
              margin-bottom: 0;
            }
          }
          
          .event-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
            
            .school-name {
              font-weight: 500;
              color: #303133;
              font-size: 16px;
            }
          }
          
          .event-details {
            .event-description {
              margin: 0 0 12px;
              color: #606266;
              line-height: 1.6;
            }
            
            .event-actions {
              text-align: right;
            }
          }
        }
      }
    }
    
    .table-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .pagination-wrapper {
        margin-top: 20px;
        text-align: right;
      }
      
      .time-info {
        color: #606266;
        font-size: 14px;
      }
      
      .no-action {
        color: #c0c4cc;
      }
      
      :deep(.el-table) {
        border: 1px solid #e4e7ed;
        border-radius: 8px;
        overflow: hidden;
        
        .el-table__header-wrapper {
          th {
            border-bottom: 2px solid #e4e7ed;
          }
        }
        
        .el-table__body-wrapper {
          .el-table__row {
            &:hover {
              background-color: #f5f7fa;
            }
            
            td {
              border-bottom: 1px solid #f0f2f5;
              padding: 16px 0;
              vertical-align: middle;
            }
          }
        }
        
        .cell {
          padding: 0 10px;
          line-height: 1.6;
        }
      }
    }
    
    .reminder-card {
      .reminder-content {
        h3 {
          margin-top: 0;
          margin-bottom: 16px;
          color: #2c3e50;
          font-size: 16px;
        }
        
        ul {
          padding-left: 20px;
          
          li {
            margin-bottom: 8px;
            line-height: 1.6;
            color: #6c757d;
            
            strong {
              color: #495057;
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .schedule-page {
    .page-header {
      padding: 40px 0;
      
      h1 {
        font-size: 2rem;
      }
      
      .subtitle {
        font-size: 1rem;
      }
    }
    
    .filter-card {
      .el-form {
        .el-form-item {
          display: block;
          margin-right: 0;
          margin-bottom: 16px;
        }
      }
    }
    
    .timeline-card {
      .card-header {
        flex-direction: column;
        gap: 12px;
        align-items: flex-start;
      }
      
      .timeline-content {
        .events-list {
          .event-item {
            padding: 12px;
          }
          
          .event-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 8px;
            
            .school-name {
              font-size: 14px;
            }
          }
        }
      }
    }
    
    .table-card {
      .card-header {
        flex-direction: column;
        gap: 12px;
        align-items: flex-start;
      }
    }
    
    .reminder-card {
      .reminder-content {
        .el-row {
          .el-col {
            margin-bottom: 20px;
          }
        }
      }
    }
  }
}
</style>